<template>
  <div class="app-container">
    <!-- 搜索模块 -->
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="模板名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="模板名称" size="small" style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="使用场景" prop="scene">
        <el-select v-model="queryParams.scene" placeholder="使用场景" size="small" style="width: 240px">
          <el-option v-for="dict in sceneOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 图标权限模块 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['admin:budget:form:add:post']" type="primary" plain icon="el-icon-upload" size="mini"
          @click="handleAdd">模板导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['admin:budget:form:delete:{id}:delete']" type="danger" plain icon="el-icon-delete"
          size="mini" :disabled="multiple" @click="handleDelete">批量删除
        </el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>
    <!-- 展示模块 -->
    <el-table v-loading="loading" :data="formworkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板名称" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <router-link
            :to="hasPermi(['admin:budget:form:model:list:post']) ? '/budget/formwork/data/' + scope.row.id : '#'"
            class="link-type">
            <span>{{ scope.row.name }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="使用场景" align="center" prop="scene" :formatter="sceneFormat" />
      <el-table-column
        v-if="hasPermi(['admin:budget:form:edit:post', 'system:clearsavefile:download:post', 'admin:budget:form:delete:{id}:delete'])"
        label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button v-hasPermi="['admin:budget:form:edit:post']" size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-hasPermi="['system:clearsavefile:download:post']" size="mini" type="text" icon="el-icon-download"
            @click="handleDownload(scope.row)">下载
          </el-button>
          <el-button v-hasPermi="['admin:budget:form:delete:{id}:delete']" size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 文件上传|修改 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="模板名称" />
        </el-form-item>
        <el-form-item label="使用场景" prop="scene">
          <el-select v-model="form.scene" placeholder="使用场景" style="width: 100%;">
            <el-option v-for="dict in sceneOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板导入" prop="path" v-if="this.form.id == undefined">
          <el-upload class="upload-demo" drag ref="uploadRef" :http-request="chunkUpload" :action="uploadUrl"
            :data="uploadData" :on-success="handleSuccess" :on-error="onError" name="file" :headers="headers"
            accept=".xlsx, .xls, .csv">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传xls/xlsx/csv文件，且列名不能重复</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
import { listType, inspectHeaderAll, addType, dataEche, editType, delType } from "@/api/vadmin/budget/formwork/formworkapi";
import chunkUpload from '@/utils/chunkUpload'
import { getToken } from "@/utils/auth";
import { Decrypt } from "@/utils/AesHmacMD5";

export default {
  name: "formwork",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      valNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模板表格数据
      formworkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 场景数据字典
      sceneOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,  // 当前页数
        pageSize: 10,  // 每页显示几个
        name: undefined,
        scene: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        scene: [
          { required: true, message: "使用场景不能为空", trigger: "blur" }
        ],
        path: [
          { required: true, validator: this.validatorPath(), trigger: "blur" }
        ]
      },
      chunkUpload: chunkUpload, // 文件上传
      uploadUrl: process.env.VUE_APP_BASE_API + '/admin/system/upload_fileM/', //文件上传的路径
      uploadData: {},
      headers: {
        Authorization: "Bearer " + getToken()
      },
    };
  },
  created() {
    // 初始化模板列表
    this.getList();
    // 查询应用场景字典
    this.getDicts("explorate_type").then(response => {
      this.sceneOptions = response.data;
    });
  },
  methods: {
    validatorPath() {
      return (rule, value, callback) => {
        if (this.form.id == undefined && !value) {
          return callback(new Error("模板文件不能为空"));
        } else {
          callback();
        }
      }
    },
    /** 查询模板文件列表 */
    getList() {
      this.loading = true;
      listType(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        var resData = JSON.parse(Decrypt(response.data))
        this.formworkList = resData.results;
        this.total = resData.count;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        scene: undefined,
        path: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 文件上传按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "模板导入";
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$refs.uploadRef.clearFiles()
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this, this.form.id == undefined) {
            addType(this.form).then(response => {
              this.msgSuccess(response.msg);
              this.open = false;
              this.getList();
            });
          } else {
            editType(this.form).then(response => {
              this.msgSuccess(response.msg);
              this.open = false;
              this.getList();
            })
          }
        }
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.valNames = selection.map(item => item.formCode);
      this.single = selection.length !== 1;
      this.multiple = selection.length < 2;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.name || this.valNames
      this.$confirm('是否确认删除模板编码为"' + names + '"的数据项? 录入数据也随之删除，请谨慎操作！', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delType(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      });
    },
    // 场景字典翻译
    sceneFormat(row, column) {
      return this.selectDictLabel(this.sceneOptions, row.scene);
    },
    /** 文件下载 **/
    handleDownload(row) {
      this.download(row.path, row.name);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // const id = row.id || this.ids;
      dataEche({ "id": row.id }).then((response) => {
        this.form = JSON.parse(Decrypt(response.data));
        this.open = true;
        this.title = "模板修改";
      });
    },
    /** 文件上传成功调用的钩子函数 */
    handleSuccess(data) {
      inspectHeaderAll({ 'path': data.saveFile }).then(response => {
        var resData = JSON.parse(Decrypt(response.data))
        if (resData.bol) {
          this.form.path = data.saveFile
          this.$message.success('文件上传成功！');
          this.$refs.uploadRef.clearFiles()
        } else {
          this.onInspect(resData.repeat_values)
        }
      })

    },
    /** 文件上传失败调用的钩子函数 */
    onError() {
      this.form.path = undefined
      this.$message.error('文件上传失败！');
      this.$refs.uploadRef.clearFiles()
    },
    /** 重复列回显函数 */
    onInspect(data) {
      this.form.path = undefined
      this.$message.error('文件' + data + '列重复，请检查之后重新上传！');
      this.$refs.uploadRef.clearFiles()
    }
  }
};
</script>
  